package com.common.library.util;

import java.io.IOException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import com.zs4sdk.entity.Zs4GameData;
import com.common.library.sun.misc.BASE64Decoder;
import com.common.library.sun.misc.BASE64Encoder;

public class DES {

	private static final String desKey = Zs4GameData.getInstance().getAppKey();

//	public DES(String desKey) {
//		this.desKey = desKey.getBytes();
//	}

	public static byte[] desEncrypt(byte[] plainText) {
		SecureRandom sr = new SecureRandom();
		byte rawKeyData[] = desKey.getBytes();
		byte encryptedData[] = null;
		try {
			DESKeySpec dks = new DESKeySpec(rawKeyData);
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey key = keyFactory.generateSecret(dks);
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(Cipher.ENCRYPT_MODE, key, sr);
			byte data[] = plainText;
			encryptedData = cipher.doFinal(data);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return encryptedData;
	}

	public static byte[] desDecrypt(byte[] encryptText) {
		SecureRandom sr = new SecureRandom();
		byte rawKeyData[] = desKey.getBytes();
		byte decryptedData[] = null;
		try {
			DESKeySpec dks = new DESKeySpec(rawKeyData);
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey key = keyFactory.generateSecret(dks);
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(Cipher.DECRYPT_MODE, key, sr);
			byte encryptedData[] = encryptText;
			decryptedData = cipher.doFinal(encryptedData);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return decryptedData;
	}

	public static String encrypt(String input) {
		return base64Encode(desEncrypt(input.getBytes()));
	}

	public static String decrypt(String input) {
		byte[] result = null;
		try {
			result = base64Decode(input);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new String(desDecrypt(result));
	}

	public static String base64Encode(byte[] s) {
		if (s == null)
			return null;
		BASE64Encoder b = new BASE64Encoder();
		return b.encode(s);
	}

	public static byte[] base64Decode(String s) throws IOException {
		if (s == null)
			return null;
		BASE64Decoder decoder = new BASE64Decoder();
		byte[] b = decoder.decodeBuffer(s);
		return b;
	}
//
//	public static void main(String[] args) throws Exception {
//		String key = "63310777cloudtop63310777cloudtop";
//		// String input = "a";
//		DES crypt = new DES(key);
//		System.out.println("Encode:" + crypt.encrypt("test123"));
//		// System.out.println("Decode:" + crypt.decrypt("xPI+nFVJj/I="));
//	}
}